#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <uuid/uuid.h>
#include "process.h"
#include <map>
#include <utility>
#include "publicFunc.h"
#include <algorithm>

using namespace std;


void getProcess(sqlite3*db, char *Mac, vector<pAttackIP>&vtAttackIP, char *eventId)
{
	if(db == NULL)
		return;
	
	system("sudo netstat -aluntp >port");
	
	vector<pair<string, string> > vtPid;
	vector<pair<string, string> >::iterator it0;
	vector<pAttackIP>::iterator it1;
	FILE *fp2 = NULL;
	fp2 = fopen("./port", "r");
	if(fp2 == NULL)
	{
		perror("open port file err");
	}
	else
	{
		char remote_Port[20];
		char prc_path[256];
		char prc_id[20];
		char Local_ip[32];
		char Local_port[32];
		char remote_ip[32];
		char status[20];
		char protocol[20];
		char Line2[1024];
		char *err_msg = NULL;
		memset(Line2, 0, sizeof(Line2));
		bool flag = false;
		char abnormal_flag[20];
		char field[256];
		memset(field, 0, sizeof(field));
		int j = 0;
		int m = 0;
		while(fgets(Line2, 1024-1, fp2) != NULL)
		{

		char cUUID[36];
		memset(cUUID, 0, sizeof(char)*36);
		uuid_t uuid;
		uuid_generate(uuid);
		uuid_unparse(uuid, cUUID);
		string temp(cUUID);
		temp.erase(remove(temp.begin(), temp.end(), '-'));
		memset(cUUID, 0, sizeof(cUUID));
		strncpy(cUUID, temp.c_str(), 32);
			pair<string, string> pr;
			if(flag)
			{
				string strLine(Line2);
               			j = 0;
              		 	m = 0;
				for(int i = 0; i < strLine.size(); i++)
				{
					
					if(Line2[i] != ' ' && Line2[i] != '\n')
					{
                    				field[m] = Line2[i];
                        			m++;
					}
					else if(Line2[i] == ' ' && Line2[i-1] == ' ')
						continue;
					else
					{
						switch(j)
                        			{
						   	case 0:
							{
								//cout<<field<<endl;
							memset(protocol,0,20);
							strcpy(protocol,field);
								break;
							}
							 case 1:
							{
								//cout<<field<<endl;
								break;
							}
							case 2:
							{
								//cout<<field<<endl;
								break;
							}
							case 3:
							{
								cout<<field<<endl;
								string strLocalIp = StrLeft(field, strReverseFind(field, ":"));
								memset(Local_ip,0,32);

								strcpy(Local_ip,strLocalIp.c_str());
								char * p = strrchr(field,':')+1;

								memset(Local_port,0,20);
								strcpy(Local_port,p);

								//cout<<Local_ip<<endl;
								//cout<<Local_port<<endl;
								break;
							}
							case 4:
							{
								//cout << field << endl;
								string strIp = StrLeft(field, strReverseFind(field, ":"));
												pr.first = strIp;
								memset(remote_ip,0,32);
								strcpy(remote_ip,strIp.c_str());

								memset(remote_Port,0,20);
								char *p =strrchr(field,':')+1;
								strcpy(remote_Port,p);
								//cout<<remote_Port<<endl;
								//cout << "ip=" << strIp << endl;
								break;
							}
							case 5:
							{

								
								if(strstr(protocol, "udp"))
								{
									memset(status,0,20);
									strcpy(status,"");
									if(strFind(field, "/") >= 0)
									{
									    	string strPid = StrLeft(field, strFind(field, "/"));
														pr.second = strPid;
														vtPid.push_back(pr);
										memset(prc_id,0,20);
										strcpy(prc_id,strPid.c_str());
						
										memset(prc_path,0,256);
										char *p = strrchr(field,'/')+1;
										strcpy(prc_path,p);
								
									    cout << "prc_path = " << prc_path << endl;
									}
								}
								else
								{
									cout<<field<<endl;
									memset(status,0,20);
									strcpy(status,field);
								}
								break;
							}
						    case 6:
						    {
						        //cout << field << endl;
						        if(strFind(field, "/") >= 0)
						        {
						            	string strPid = StrLeft(field, strFind(field, "/"));
												pr.second = strPid;
												vtPid.push_back(pr);
								memset(prc_id,0,20);
								strcpy(prc_id,strPid.c_str());
						
								memset(prc_path,0,256);
								char *p = strrchr(field,'/')+1;
								strcpy(prc_path,p);
								
						            cout << "prc_path = " << prc_path << endl;
						        }
						        break;
						    }
						}
						memset(field, 0, sizeof(field));
						m=0;
						j++;
					}
				}
				if(strcasecmp(remote_ip,Local_ip)!=0&&strcasecmp(remote_ip,"0.0.0.0")!=0&&strcasecmp(remote_ip,"::")!=0)
					{
						strcpy(abnormal_flag,"1");
					}
					else
					{
						strcpy(abnormal_flag,"0");
					}
				char Sql[1024];
				memset(Sql,0,1024);
				snprintf(Sql, 1023, "insert into linux_port_info (id, local_ip,local_port, remote_ip, remote_port, prc_id, state, prc_path, protocol,abnormal_flag, mac_address,event_task_id) values('%s', '%s','%s', '%s','%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')", cUUID, Local_ip,Local_port, remote_ip, remote_Port, prc_id, status,  prc_path,protocol,abnormal_flag, Mac, eventId); 
							
			

				int ret = sqlite3_exec(db, Sql, NULL, NULL, &err_msg);
cout<<Sql<<endl;
			    	if(ret != SQLITE_OK)
			    	{
				    perror(err_msg);
				    sqlite3_free(err_msg);
				}
			}
			if(strFind(Line2, "Proto") >= 0)
				flag = true;
			
			memset(Line2, 0, sizeof(Line2));

		}
        fclose(fp2);
	}
	system("rm port");

	system("ps -aux >pcs");
	char * FilePath = "./pcs";

	FILE *fp = NULL;
	fp = fopen(FilePath, "r");
	if(fp == NULL)
	{
		perror("open file err");
		return;
	}
	char Line[1024];
	memset(Line, 0, sizeof(Line));
	int i = 0;

	char User[32] = {0};
	char Pid[16] = {0};
	char Mem[8] = {0};
	char Cpu[8] = {0};
	char Time[32] = {0};
	char Command[512] = {0};
	char Sql[1024] = {0};
	char *err_msg = NULL;
	char Ip[64] = {0};
	while(fgets(Line, 1023, fp) != NULL)
	{
		//cout<<Line<<endl;
		//cout << Line;
		if(i == 0)
		{
			memset(Line, 0, sizeof(Line));
			i++;
			continue;
		}
		memset(User, 0, sizeof(User));
		memset(Pid, 0, sizeof(Pid));
		memset(Mem, 0, sizeof(Mem));
		memset(Cpu, 0, sizeof(Cpu));
		memset(Time, 0, sizeof(Time));
		memset(Command, 0, sizeof(Command));
		memset(Sql, 0, sizeof(Sql));
		string line(Line);
		char field[256];
		memset(field, 0, sizeof(field));
		int j = 0;
		int m = 0;
		for(int n = 0; n < line.size(); n++)
		{
			if((j == 10 || line[n] != ' ') && line[n] != '\n')
			{
				field[m] = line[n];
				m++;
			}
			else if(line[n] == ' ' && line[n-1] ==' ')
				continue;
			else
			{
				switch(j)
				{
					case 0:		// 所属用户
					{
						//cout << field << endl;
						strncpy(User, field, 31);
						//cout<<User<<endl;
						break;
					}
					case 1:		// Pid
					{
						//cout << field << endl;
						strncpy(Pid, field, 15);
						break;
					}
					case 2:		// cpu使用率 百分比
					{
						//cout << field << endl;
						strncpy(Cpu, field, 7);
						break;
					}
					case 3:		// 内存使用率 百分比
					{
						//cout << field << endl;
						strncpy(Mem, field, 7);
						break;
					}
					case 8:		// 进程开始时间
					{
						//cout << field << endl;
						strncpy(Time, field, 31);
						break;
					}
					case 10:	// 执行的命令
					{
						//cout << field << endl;
						strncpy(Command, field, 511);
						break;
					}
				}
				memset(field, 0, sizeof(field));
				m = 0;
				j++;
			}
		}
		// 是否违规
		int isGetOut = 0;
		// UUID
        char cUUID[36];
        memset(cUUID, 0, sizeof(char)*36);
        uuid_t uuid;
        uuid_generate(uuid);
        uuid_unparse(uuid, cUUID);
		string temp(cUUID);
		temp.erase(remove(temp.begin(), temp.end(), '-'));
		memset(cUUID, 0, sizeof(cUUID));
		strncpy(cUUID, temp.c_str(), 32);

		memset(Ip, 0, sizeof(Ip));
		for(it0 = vtPid.begin(); it0 != vtPid.end(); it0++)
		{
			if(strcmp(Pid, (*it0).second.c_str()) == 0)
			{
				strncpy(Ip, (*it0).first.c_str(), 64-1);
			}
		}
		for(it1 = vtAttackIP.begin(); it1 != vtAttackIP.end(); it1++)
		{
			if(strcmp(Time,(*it1)->firstTime) >= 0 && strcmp(Time,(*it1)->lastTime) <= 0)
			{
				isGetOut = 1;
				break;
			}
		}
		
		if(strcasecmp(Ip,"0.0.0.0")!=0&&strlen(Ip)>1&&strcasecmp(Ip,"::")!=0)
		{
			isGetOut = 1;
		}
		StrReplace(Command, "'", "''");
		snprintf(Sql, 1023, "insert into Linux_Process_Info (id, create_user,name, pid, ip_from, cpu_use, mem_use, process_create_time, is_get_out, mac_address, event_task_id) values('%s', '%s', '%s','%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s')", 
			cUUID, User,Command, Pid, Ip, Cpu, Mem, Time, isGetOut, Mac, eventId);
		int ret = sqlite3_exec(db, Sql, NULL, NULL, &err_msg);
    	if(ret != SQLITE_OK)
    	{
            perror(err_msg);
            sqlite3_free(err_msg);
        }
		
		memset(Line, 0, sizeof(Line));
		++i;
	}
	fclose(fp);

	system("rm pcs");

	return;
}
